
import Vconsole from "vconsole";
import Vue from "vue";
import { isAndroidDevice,
    isIOSMobile
} from '@/utils/helper'

let count = 0;
export function debounceTimes(fn, delay, totalCount) {
    // 利用闭包保存定时器
    let timer = null;
    return function() {
        let context = this;
        let arg = arguments;
        // 在规定时间内再次触发会先清除定时器后再重设定时器
        clearTimeout(timer);
        count = count + 1;
        timer = setTimeout(function() {
            if(count > totalCount) {
                const vConsole = new Vconsole()
                Vue.use(vConsole)
                count = 0;
            }
            fn.apply(context, arg);
        }, delay);
    };
}

export function  getCustomUAParam(name, ua) {
    const regex = new RegExp( name +":(.*);?(.*)")
    const results = regex.exec(ua)
    if(results) {
        const map = results[0].split(";")[0].split(":");
        console.warn("results---->", map[1]);
        return map[1];
    }else {
        return ""
    }
}

/**
 * fontNum: -1 0 1 2 3 4 5等
 * @returns {number}
 */
export function getIOSFontScale() {
    var ua = navigator.userAgent;
    var fontNum = getCustomUAParam('fontNum', ua);
    if(fontNum) {
        return 1 + fontNum / 16;
    }
    return 1;
}

export function  getFontScale() {
    var ua = navigator.userAgent;
    var scale = 1;
    var scaleStr = "";
    var isAndroid = isAndroidDevice();
    try {
        if(isAndroid) {
            scaleStr = getCustomUAParam('scale', ua);
            if(scaleStr){
                scale = parseFloat(scaleStr);
            }
            return scale;
        }
        if(isIOSMobile()) {
            scale = getIOSFontScale();
            return scale;
        }
        return scale;
    } catch (e) {
        return scale;
    }
}